<template>
  <div
    class="resource-step-container w-full h-full overflow-hidden flex justify-start items-center flex-col"
  >
    <div
      class="resource-step-title w-full h-[52px] pt-[16px] pb-[16px] pl-[24px] pr-[24px] flex justify-between items-center box-border"
    >
      关联信息
    </div>
    <div
      class="content-box w-full h-[calc(100%_-_116px)] pl-[24px] pr-[24px] box-border overflow-hidden overflow-y-auto m-height-0"
      ref="RefOutBox"
    >
      <div
        class="table-box w-full overflow-y-auto overflow-hidden box-border flex flex-col"
        ref="RefTableBox"
      >
        <a-form
          :model="handlerData"
          :label-col-props="{ span: 0 }"
          :wrapper-col-props="{ span: 24 }"
          ref="RefFormBox"
        >
          <a-table
            :columns="Columns"
            :data="handlerData"
            :pagination="false"
            :scroll="{ x: 0, y: '100%' }"
            class="table-box-inner"
            @row-click="tableRowClick"
          >
            <template #index="{ rowIndex }">{{ rowIndex + 1 }}</template>

            <template #relation="{ record, rowIndex }">
              <a-form-item
                class="ckd-custom-table-item"
                :validate-status="status[rowIndex][1] as any"
                feedback
              >
                <a-select
                  v-model="handlerData[rowIndex].relation"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <a-option value="parent" v-if="!(props.formData.is_root == 1)">上级</a-option>
                  <a-option value="next" :disabled="checkIdISRoot(+record.id)">下级</a-option>
                </a-select>
              </a-form-item>
            </template>

            <template #id="{ rowIndex }">
              <a-form-item
                class="ckd-custom-table-item"
                :validate-status="status[rowIndex][0] as any"
                :feedback="true"
              >
                <a-select
                  v-model="handlerData[rowIndex].id"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <template v-for="item in resourceList" :key="item.id">
                    <a-option
                      :value="+item.id"
                      :disabled="!checkOptionShow(item.id, rowIndex) || (item as any).disabled"
                    >
                      {{ item.name }} (V{{ item.version }}.0)
                    </a-option>
                  </template>
                </a-select>
              </a-form-item>
            </template>
            <template #operator="{ record, rowIndex }">
              <a-link type="primary" @click="removeRow(record, rowIndex)">删除</a-link>
            </template>
          </a-table>
        </a-form>
      </div>
      <a-button class="w-full mt-[20px] add-button-box" @click="addRow">
        <!-- <icon-plus />添加 -->
        新增一行
      </a-button>
    </div>
    <div class="footer-box w-full h-[64px] flex justify-between items-center pl-[24px] pr-[24px]">
      <span></span>
      <span>
        <a-button class="mr-2" @click="$router.push({ name: 'resource' })"
          >取消</a-button
        >
        <a-button class="mr-2" @click="emits('toPrev')">上一步</a-button>
        <a-button type="primary" class="ml-2" @click="toSubmit">完成</a-button>
      </span>
    </div>
  </div>
</template>

<script lang="ts" setup>
import * as Api from '@/api/assetManagement';
import type { PropType } from 'vue';
import { onMounted, ref, watch } from 'vue';
import { Columns, CreateColumnData } from '../values';

const props = defineProps({
  formData: {
    type: Object as PropType<Api.TResourceItem>,
    required: true
  }
});
const emits = defineEmits(['update:formData', 'submit', 'toPrev']);
const handlerData = ref<any[]>([]);
const RefOutBox = ref<HTMLDivElement>();
const RefTableBox = ref<HTMLDivElement>();
const activeRow = ref(0);
const resourceList = ref<Api.TResourceItem[]>([]);
const RefFormBox = ref<any>();
const status = ref<any[][]>([]);

function checkOptionShow(id: any, index: number) {
  // 不能选择自己
  if (id == props.formData.id) return false;
  // 不能选择重复的
  const index1 = handlerData.value.findIndex((v, i) => v.id == id && i !== index);
  if (index1 > -1) return false;
  // 如果选择的relation 是next 则不能选择根节点
  if (handlerData.value[index].relation == 'next' && checkIdISRoot(id)) return false;
  return true;
}

// 判断是否是根节点
function checkIdISRoot(id: any) {
  const item = resourceList.value.find((v) => v.id === id);
  if (!item) return false;
  return item.is_root == 1;
}

function tableRowClick(row: any) {
  activeRow.value = row.index;
}

function addRow() {
  const index = handlerData.value.length + 1;
  status.value.push([undefined, undefined]);
  handlerData.value.push({
    index,
    ...CreateColumnData()
  });
  activeRow.value = index;
}

function removeRow(d: any, index: number) {
  // const { index } = d
  handlerData.value.splice(index, 1);
  status.value.splice(index, 1);
}

function toSubmit() {
  if (!RefFormBox.value) {
    return;
  }
  let res = true;
  handlerData.value.forEach((v, i) => {
    if (v.id == '' && v.relation == '') return;
    if (v.id && !v.relation) {
      status.value[i][1] = 'error';
      res = false;
      return;
    }
    if (!v.id && v.relation) {
      status.value[i][0] = 'error';
      res = false;
      return;
    }
  });
  if (!res) return;
  emits('submit', { ...handlerData.value });
}

function getResources(cb?: any) {
  // 获得全部资源
  Api.getList({ page: 1, page_size: 1e2 }, {}).then((res) => {
    const { code, data } = res;
    if (code !== 200 || !data) return;
    resourceList.value = data;
    cb ? cb() : false;
  });
}

function getRelations() {
  Api.GetRelation(props.formData.id).then((res) => {
    const { code, data } = res;
    if (code !== 200 || !data) return;
    const parent_ids: string[] = [];
    data.forEach((v: any, i: number) => {
      if (v.currently) {
        if (v.parent_id) {
          parent_ids.push(...v.parent_id);
        }
        return;
      }

      // 添加至 resourceList
      if (!resourceList.value.find((item) => item.id == v.id)) {
        resourceList.value.push({ ...v, id: +v.id, disabled: true });
      }
      console.log(`[ resourceList.value ]=>`, resourceList.value);

      const index = parent_ids.findIndex((id) => id == v.id);
      if (index > -1) {
        handlerData.value.push({
          id: +v.id,
          relation: 'parent',
          index: handlerData.value.length + 1
        });
        status.value.push([undefined, undefined]);
        return;
      }
      handlerData.value.push({
        id: +v.id,
        relation: 'next',
        index: handlerData.value.length + 1
      });
      status.value.push([undefined, undefined]);
    });
  });
}

watch(
  handlerData,
  (val) => {
    if (!val) return;
    if (val.length === 0) {
      emits('update:formData', { ...props.formData, relations: [] });
      return;
    }
    const relations: any[] = [];
    val.forEach((v, i) => {
      const { id, relation } = v;
      if (!id || !relation) return;
      relations.push({ [`${relation}_id`]: id });
    });
    emits('update:formData', { ...props.formData, relations });
  },
  { deep: true }
);

onMounted(() => {
  getResources(() => {
    if (!props.formData.id) return; // 传入的不是编辑数据
    getRelations();
  });
});
</script>

<style lang="less" scoped>
.table-box-inner {
  :deep(.arco-table-td-content) {
    .arco-select {
      @apply bg-white;
      border: 1px solid #d3dbeb;
      border-radius: 4px;
    }
  }
}
.resource-step-container {
  .resource-step-title {
    font-family: Microsoft YaHei;
    font-size: 14px;
    font-weight: bold;
    color: #394d73;
  }
  .content-box {
    .table-box {
      max-height: calc(100% - 62px) !important;
    }
  }
  .footer-box {
    box-shadow: 0px 0px 6px 0px rgba(57, 77, 115, 0.1);
  }
}
.add-button-box {
  background-color: #F0F4FA;
  border: 1px dotted #d3dbeb;
  border-radius: 4px;
  color: #465A80;
}
.ckd-custom-table-item {
  margin: 0;
}
.arco-form-item-status-error {
  :deep(.arco-select) {
    border-color: #f5222d !important;
  }
  .arco-form-item-wrapper-col {
    .arco-form-item-content-wrapper {
      .arco-form-item-content {
      }
    }
  }
}
</style>
